const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()

exports.main = async (event, context) => {
    const { searchText } = event

    if (!searchText) {
        return {
            code: 400,
            message: '请输入有效的搜索文本'
        }
    }

    try {
        // 构建查询条件
        const buildQuery = (collection) => {
            const conditions = []

            // 检查字段是否存在并添加查询条件
            const fields = ['tags', 'title', 'desc', 'name']
            fields.forEach(field => {
                conditions.push({
                    [field]: db.RegExp({ regexp: searchText, options: 'i' })
                })
            })

            return db.collection(collection)
                .where({
                    $or: conditions
                })
        }

        // 并行查询两个集合
        const [industryResults, templateResults] = await Promise.all([
            buildQuery('industry_resume_template').get(),
            buildQuery('resume_templates').get()
        ])

        return {
            code: 200,
            data: [
                ...industryResults.data,
                ...templateResults.data
            ]
        }
    } catch (err) {
        console.error('搜索模板出错:', err)
        return {
            code: 500,
            message: '搜索模板失败',
            error: err.message
        }
    }
}